Analysis of Common Loops
Python
for i in range(0, n, c):
# some constant work
JavaScript
for (let i = 0; i < n; i += c) {
// some constant work
}
- Example: for
n = 10
andc = 2
, it will run5
times(0, 2, 4, 6, 8)
. - Time complexity for this loop is . Ignoring constants, it’s .
Python
for i in range(n, 0, c) # where c is negative value
# some constant work
JavaScript
for (let i = n; i > 0; i -= c) {
// some constant work
}
- Example: for
n = 10
andc = 2
, it will run5
times(10, 8, 6, 4, 2)
. - Time complexity for this loop is . Ignoring constants, it’s .
Python
i = 1
while i < n:
# some constant work
i *= c
JavaScript
for (let i = 1; i < n; i *= c) {
// some constant work
}
-
Example: For
n = 32
andc = 2
, it will be executed5
times1, 2, 4, 8, 16
. Forn = 33
andc = 2
, it will be executed6
times1, 2, 4, 8, 16, 32
. Generalizing, it runs for i.e. it runs times from to .So, the loop is going to run times.
-
Time complexity for this loop is .
-
Note that base of the log doesn’t matter, since bases can be converted by simple multiplication or division operations and in asymptotic analysis constants are ignored.
Python
i = n
while i > 1:
# some constant work
i //= c # // is integer division
JavaScript
for (let i = n; i > 1; i /= c) {
// some constant work
}
- Example:
Forn = 32
andc = 2
, it will be executed5
times32, 16, 8, 4, 2
. Forn = 33
andc = 2
, it will be executed6
times 33, 16, 8, 4, 2`. - Time complexity for this loop is .
Python
i = 2
while i < n:
# some constant work
i = pow(i, c)
JavaScript
for (let i = 2; i < n; i = Math.pow(i, c)) {
// some constant work
}
-
Example: For
c = 2
andn = 32
it’s going to run for i.e.2, 4, 16
.Let’s find out the number of times the loop runs:
-
Time complexity of this loop is .
Python
def fun(n):
for i in range(n): # 𝛳(n)
# some constant work
i = 0
while i < n: # 𝛳(log n)
# some constant work
i *= 2
for i in range(1, 100): # 𝛳(1)
# some constant work
JavaScript
function fun(n) {
for (let i = 0; i < n; i++) {
// some constant work
}
i = 0;
while(i < n) {
i *= n;
}
for (i = 0; i < 100; i++) {
// some constant work
}
}
- Since the work is sequential, we add the values
.
Ignoring lower order terms, the complexity of this function is .
Python
def fun(n):
for i in range(n): # 𝛳(n)
j = 0
while j < n: # 𝛳(log n)
# some constant work
j *= 2
JavaScript
function fun(n) {
for(let i = 0; i < n; i++) {
let j = 0;
while(j < n) {
j *= 2;
}
}
}
- Since it’s a nested loop,we multiply the values
.
Therefore the complexity is .
Python
def fun(n):
for i in range(n): # 𝛳(n)
for j in range(n): # 𝛳(n)
# some constant work
JavaScript
function fun(n) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
// some constant work
}
}
}
- The time complexity is .